package com.chexiang360.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.session.JdbcSessionDataSourceInitializer;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSON;

/**
 * @author Watler
 * @apiNote 接口公用类
 */
public abstract class BaseController {
	Logger logger = LoggerFactory.getLogger(getClass());
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;


	public String errorUrl;// 错误返回url

	// 页面表单存放数据
	protected Map<String, String> paramMap = new HashMap<String, String>();

	//存储所有用户的cookie
	protected static HashMap<String, String> hashMap = new HashMap<String, String>();

	/**
	 * 以MAP的格式，接收所有参数
	 * @return
	 */
	protected Map<String, String> getRequestMap() {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> enumeration = this.request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String name = enumeration.nextElement();
			map.put(name, request.getParameter(name));
		}
		return map;
	}
	/**
	 * 数据流类型输出
	 * @param str
	 */
	public void toWrite(String str) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			pw.write(str);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * JOSN类型输出
	 * @param obj
	 */
	protected void writeJson(Object obj) {
		String jsonString = JSON.toJSONString(obj); 
		logger.info("json输出数据==>" + jsonString);
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/x-json;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			pw.write(jsonString);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


	public Map<String, String> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, String> paramMap) {
		this.paramMap = paramMap;
	}

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
		this.request = request;
		this.response = response;
		this.session = request.getSession();
	}

}